package com.sun.aidlclient

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.sun.aidlmode.UserManager

class MainActivity : AppCompatActivity() {

    private  val btnGetUser by lazy { findViewById<Button>(R.id.ids_get_user)}

    private  val btnAddUser by lazy { findViewById<Button>(R.id.ids_add_user)}

    private  val textView by lazy { findViewById<TextView>(R.id.ids_text) }
    private  val editName by lazy { findViewById<EditText>(R.id.ids_ed_user_name) }
    private  val editAge by lazy { findViewById<EditText>(R.id.ids_ed_user_age) }

    private   var  userManager:UserManager?=null
    private  val serviceConn = object :ServiceConnection{
        override fun onServiceDisconnected(name: ComponentName?) {
            userManager = null
            textView.text = "连接断开"
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
           userManager = UserManager.Stub.asInterface(service)
            textView.text = "连接成功"
        }

    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val intent = Intent(ACTION_USER).apply {
            setPackage(SERER_PACKAGE)
        }
        bindService(intent,serviceConn,Context.BIND_AUTO_CREATE)
        btnGetUser.setOnClickListener { getUser() }
        btnAddUser.setOnClickListener { addUser() }
    }

    private fun addUser(){
       if(editAge.text.isNotEmpty() && editName.text.isNotEmpty()){
           userManager?.let {
               it.addUser(editName.text.toString(),editAge.text.toString().toInt())
               textView.text = "添加成功"
           }
       }else{
           Toast.makeText(this,"名字或者年龄为空",Toast.LENGTH_SHORT).show()
       }
    }
    private fun  getUser(){
        userManager?.let {
           textView.text =  it.allUsers.toString()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        userManager?.let {
            unbindService(serviceConn)
            userManager = null
        }
    }
}
